<template>
  <!-- 添加或修改用户配置对话框 -->
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="55%"
    append-to-body
    @close="handleClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="nickName">
            <el-input
              v-model.trim="form.nickName"
              placeholder="请输入姓名"
              maxlength="10"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别">
            <el-select
              v-model="form.sex"
              placeholder="请选择性别"
              class="full-width"
            >
              <el-option
                v-for="dict in dict.type.sys_user_sex"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <!-- 新增时展示 -->
          <el-form-item label="账号" prop="userName">
            <el-input
              v-model="form.userName"
              placeholder="请输入账号"
              minlength="8"
              maxlength="11"
            />
          </el-form-item>
          <!-- 修改时展示 -->
          <!-- <el-form-item v-if="form.userId != undefined" label="账号" prop="userName">
              <el-input disabled v-model="form.userName" />
            </el-form-item> -->
        </el-col>
        <el-col :span="12">
          <!-- 新增时展示 -->
          <el-form-item v-if="!form.userId" label="密码" prop="password">
            <el-input
              v-model="form.password"
              placeholder="请输入密码"
              type="password"
              minlength="12"
              maxlength="20"
              show-password
            />
          </el-form-item>
          <!-- 修改时展示 -->
          <el-form-item v-if="form.userId" label="密码">
            <el-input
              disabled
              placeholder="************"
              type="password"
              maxlength="20"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30" />
            </el-form-item>
          </el-col> -->
        <el-col :span="12">
          <el-form-item label="角色" prop="roleIds" class="full-width">
            <el-select
              v-model="form.roleIds"
              multiple
              placeholder="请选择角色"
              class="full-width"
            >
              <el-option
                v-for="item in roleOptions"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
                :disabled="item.status == 1"
              ></el-option>
            </el-select> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="form.phonenumber"
              placeholder="请输入手机号码"
              minlength="11"
              maxlength="11"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input
              v-model="form.remarks"
              type="textarea"
              placeholder="请输入备注信息"
              :autosize="{ minRows: 1, maxRows: 5 }"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="管理区域" prop="productionBaseId">
            <el-cascader
              v-model="areaSelect"
              :options="baseTreeList"
              :show-all-levels="true"
              :props="{
                expandTrigger: 'hover',
                checkStrictly: true,
                value: 'id',
                label: 'name',
                emitPath: false,
                multiple: true,
              }"
              placeholder="请选择管理区域"
              filterable
              clearable
              :collapse-tags="false"
              @change="handleAreaChange"
              ref="CascaderRef"
              class="full-width"
            ></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="员工照片">
            <ImageUpload v-model="form.avatar"></ImageUpload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </div>
  </el-dialog>
</template>
  
  <script>
import { getUser } from "@/api/system/user";
import { update, add } from "@/api/production/personnel";
import { baseAndPondList } from "@/api/production/base";
import ImageUpload from "@/components/ImageUpload";
export default {
  name: "production-personnel_edit ",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { ImageUpload },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    params: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      areaSelect: [], // 选择的管理区域
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      baseTreeList: [],
      queryParams: { id: undefined },
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单
      form: {},
      // 表单校验
      rules: {
        deptId: [
          { required: true, message: "行政区划不能为空", trigger: "blur" },
        ],
        roleIds: [{ required: true, message: "角色不能为空", trigger: "blur" }],
        phonenumber: [
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号必须为11位",
            trigger: "blur",
          },
          { min: 11, max: 11, message: "手机号必须为11位", trigger: "blur" },
        ],
        userName: [
          { required: true, message: "账号不能为空", trigger: "blur" },
          { min: 8, max: 11, message: "账号必须为8-11位", trigger: "blur" },
        ],
        nickName: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
          { min: 2, max: 10, message: "姓名不能为空", trigger: "blur" },
        ],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
        password: [
          {
            required: true,
            pattern:
              /^(?![A-z0-9]+$)(?=.[^%&',;=?$\x22])(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{12,20}$/,
            message:
              "密码长度必须是12位及以上包含大小写字母，特殊字符，数字的强密码",
            trigger: "blur",
          },
          {
            min: 12,
            max: 20,
            message:
              "密码长度必须是12位及以上包含大小写字母，特殊字符，数字的强密码",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    visible: {
      handler(val) {
        this.open = val;
        if (val && this.params.type == "edit") {
          this.queryParams.id = this.params.id;
          this.getDetail();
        }
        if (this.params.type === "add") {
          this.getOptions();
        }
        if (val) {
          this.getBaseTreeList();
          this.title = this.params.title;

          if (this.params.baseId) {
            this.areaSelect = [this.params.baseId];
          }
        }
      },
    },
  },
  methods: {
    /** 获取配置数据 */
    getOptions() {
      getUser().then((response) => {
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.getConfigKey("sys.user.initPassword").then((response) => {
          this.form.password = response.msg;
        });
      });
    },
    /** 获取树状结构列表 */
    getBaseTreeList() {
      baseAndPondList().then(async (res) => {
        this.baseTreeList = await this.removeEmptyChildren(res.data);

        if (this.params.pondId) {
          this.handleAreaChange([this.params.pondId]);
          this.areaSelect = [this.params.pondId];
        }
        if (this.params.baseId) {
          this.handleAreaChange([this.params.baseId]);
          this.areaSelect = [this.params.baseId];
        }
      });
    },
    // 管理区域选择
    handleAreaChange(val) {
      let findVal = this.differentiatedBaseAndPond(val, this.baseTreeList);
      this.form.productionBaseIdList = findVal.productionBaseIdList;
      this.form.culturePondIdList = findVal.culturePondIdList;
    },
    /** 区分基地数据和塘口数据 */
    differentiatedBaseAndPond(ids, nodes) {
      // 用于存放匹配到的 id
      let baseList = [];
      let pondList = [];
      function findByIds(ids, nodes) {
        ids.forEach((id) => {
          let foundInParent = false; // 标记是否已经在外层找到匹配的 id
          nodes.forEach((node) => {
            // 先检查外层对象是否匹配
            if (node.id === id) {
              baseList.push(id);
              foundInParent = true; // 如果找到，标记为在外层找到了
            }
            // 如果没有在外层找到，则继续检查 children
            if (!foundInParent && node.children && node.children.length > 0) {
              node.children.forEach((childNode) => {
                if (childNode.id === id) {
                  pondList.push(id); // 存入 child 数组
                }
              });
            }
          });
        });
      }
      findByIds(ids, nodes);
      return {
        productionBaseIdList: [...new Set(baseList)],
        culturePondIdList: [...new Set(pondList)],
      };
    },
    getDetail() {
      getUser(this.queryParams.id).then((response) => {
        this.form = response.data;
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.$set(this.form, "postIds", response.postIds);
        this.$set(this.form, "roleIds", response.roleIds);
        this.areaSelect = [
          ...response.productionBaseList.map((item) => item.id),
          ...response.culturePondList.map((item) => item.id),
        ];
        this.$nextTick(() => {
          this.$refs.form.clearValidate("userName");
        });
      });
    },
    /** 提交按钮 */
    handleSubmit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.userId) {
            update(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.$emit("success");
              if (this.params.autoClose) this.handleClose();
            });
          } else {
            add(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.$emit("success");
              this.handleClose();
            });
          }
        }
      });
    },
    // 取消按钮
    handleClose() {
      this.$emit("update:visible", false);
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
  },
};
</script>
  
  <style scoped lang="scss">
.relevance-card {
  // display: flex;
  // flex-wrap: wrap;
  // justify-content: space-around;
  & > li {
    width: 24%;
    height: 120px;
    float: left;
    margin-right: calc(4% / 3);
    margin-bottom: calc(4% / 3);
    border-radius: 3px;
    background-color: #fff;
    padding: 10px;
    box-sizing: border-box;
    box-shadow: 0 0 3px 0 rgba($color: #000000, $alpha: 0.1);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    &:nth-child(4n) {
      margin-right: 0;
    }
    &:nth-last-child(-n + 4) {
      margin-bottom: 0;
    }
    .relevance-card-content {
      width: 100%;
      display: flex;

      & > img {
        width: 70px;
        height: 70px;
        margin-right: 10px;
        flex-shrink: 0;
      }
    }
    .relevance-card-footer {
      width: 100%;
      // height: 10%;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  .first {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 46px;
    font-weight: 600;
    color: #eee;
    cursor: pointer;
  }
}
</style>